package com.beiwei.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beiwei.auto.mode.Company;
import com.beiwei.auto.mode.User;
import com.beiwei.mode.VCompany;
import com.beiwei.service.CompanyService;
import com.beiwei.service.UserService;

@Controller
@RequestMapping("/company")
public class CompanyHandler {

	@Autowired
	private UserService userService;
	@Autowired
	private CompanyService companyService;

	/*
	 * 查询出所有的公司
	 */
	@RequestMapping("/query")
	public String query(Model model) {

		List<Company> companys = null;
		try {
			companys = companyService.findAllCompany();

		} catch (Exception e) {
			e.printStackTrace();
		}

		model.addAttribute("companys", companys);
		return "companyList";
	}

	/**
	 * 添加公司
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	@RequiresPermissions("company:create")
	public String add(Model model) {

		model.addAttribute("company", new VCompany());
		return "addCompany";
	}

	/**
	 * 添加保存公司
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@RequiresPermissions("company:create")
	@ResponseBody
	public String addSave(VCompany company) {

		try {
			// 保存该公司并获取id
			if (companyService.getCompanyIdByAddCompany(company)) {

				User user = company.getAdmin();
				user.setUserCompanyId(company.getCompanyId());
				user.setUserRoleIds("3,2,1");// 给该admin用户添加所有身份
				if (userService.addUser(user)) {
					return "保存成功！";
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "操作失败";
	}

}
